<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ include file="/include/taglibs.jsp" %>
<title>部门管理</title>
<link rel="stylesheet" href="${ctx}/assets/admin/LingUI/css/jquery-ui.min.css"/>
<link rel="stylesheet" href="${ctx}/assets/admin/LingUI/css/jquery.gritter.css"/>
<script type="text/javascript" src="${ctx}/assets/admin/LingUI/js/ztree/js/jquery.ztree.core-3.5.js"></script>
<!-- 树插件核心 -->
<script type="text/javascript" src="${ctx}/assets/admin/LingUI/js/ztree/js/jquery.ztree.exedit-3.5.js"></script>
<!-- 树编辑插件 -->
<script type="text/javascript" src="${ctx}/assets/admin/LingUI/js/jquery.validate.min.js"></script>
<script type="text/javascript" src="${ctx}/assets/admin/LingUI/js/validate-methods.js"></script>
<script type="text/javascript" src="${ctx}/assets/admin/LingUI/js/input.js"></script>
<script type="text/javascript" src="${ctx}/assets/uc/js/common.js"></script>
<style>
    .profile-info-value {
        display: table-cell;
        padding: 6px 4px 6px 6px;
        border-top: 1px dotted #D5E4F1
    }
    </style>

<div class="row xtgltree">
    <div class="col-sm-3">
        <div class="widget-box widget-color-blue2" style="height:600px;min-height:420px; height:auto!important">
            <div class="widget-header">
                <h4 class="widget-title lighter smaller">部门管理</h4>
            </div>
            <div class="widget-body">
                <div class="widget-main padding-8">
                    <div class="zTreeDemoBackground">
                        <ul id="treeDemo" class="ztree"></ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xs-12 col-sm-9 widget-container-col lui-lcy" id="moxingtu">
        <div class="widget-box" style="height:600px;min-height:600px; height:auto!important">
            <div class="widget-header">
                <h4 class="widget-title bolder">部门管理</h4>
            </div>
            <div class="space-10"></div>
            <div id="home4" class="tab-pane in active">
                <div class="widget-body" id="view" style="display:none; ">
                    <div class="profile-user-info profile-user-info-striped">
                        <div class="profile-info-row">
                            <div class="profile-info-name"> 组织编号：</div>
                            <div class="profile-info-value">
                                <span id="id_view">&nbsp;</span>
                            </div>
                        </div>
                        <div class="profile-info-row">
                            <div class="profile-info-name"> 组织名称：</div>
                            <div class="profile-info-value">
                                <span id="name_view">&nbsp;</span>
                            </div>
                        </div>
                        <div class="profile-info-row">
                            <div class="profile-info-name"> 上级目录：</div>
                            <div class="profile-info-value">
                                <span id="parent_view">&nbsp;</span>
                            </div>
                        </div>
                        <div class="profile-info-row">
                            <div class="profile-info-name"> 联系人：</div>
                            <div class="profile-info-value">
                                <span id="contact_view">&nbsp;</span>
                            </div>
                        </div>
                        <div class="profile-info-row">
                            <div class="profile-info-name"> 联系电话：</div>
                            <div class="profile-info-value">
                                <span id="tel_view">&nbsp;</span>
                            </div>
                        </div>
                        <div class="profile-info-row">
                            <div class="profile-info-name"> 联系地址：</div>
                            <div class="profile-info-value">
                                <span id="address_view">&nbsp;</span>
                            </div>
                        </div>
                        <div class="profile-info-row">
                            <div class="profile-info-name"> 描述：</div>
                            <div class="profile-info-value">
                                <span id="description_view">&nbsp;</span>
                            </div>
                        </div>
                    </div>
                </div>

                <div style="display:none;" id="add">
                    <div align="center">
                        <form class="form-horizontal" method="post" action="#" id="form_dep_add" target="frmright"
                              role="form">
                            <div class="profile-user-info profile-user-info-striped">
                                <div class="profile-info-row">
                                    <div class="profile-info-name">组织名称：</div>
                                    <div class="profile-info-value">
                                        <input type="text" id="name_add" name="name" placeholder="必填项，长度不能超过12位"
                                               class="col-xs-12 col-sm-12"/>
                                    </div>
                                </div>
                                <div class="profile-info-row">
                                    <div class="profile-info-name"> 上级目录：</div>
                                    <div class="profile-info-value">
                                        <input type="text" id="pId_add" name="parent" style="display:none"/>
                                        <input type="text" id="pName_add" disabled class="col-xs-12 col-sm-12"/>
                                    </div>
                                </div>
                                <div class="profile-info-row">
                                    <div class="profile-info-name">联系人：</div>
                                    <div class="profile-info-value">
                                        <input type="text" id="contact_add" name="contact" class="col-xs-12 col-sm-12"/>
                                    </div>
                                </div>
                                <div class="profile-info-row">
                                    <div class="profile-info-name">联系电话：</div>
                                    <div class="profile-info-value">
                                        <input type="text" id="tel_add" name="tel" class="col-xs-12 col-sm-12"/>
                                    </div>
                                </div>
                                <div class="profile-info-row">
                                    <div class="profile-info-name">联系地址：</div>
                                    <div class="profile-info-value">
                                        <input type="text" id="address_add" name="address" class="col-xs-12 col-sm-12"/>
                                    </div>
                                </div>
                                <div class="profile-info-row">
                                    <div class="profile-info-name">排序：</div>
                                    <div class="profile-info-value">
                                        <input type="text" id="order_add" name="order" class="col-xs-12 col-sm-12" placeholder="必填项"/>
                                    </div>
                                </div>
                                <div class="profile-info-row">
                                    <div class="profile-info-name"> 描述：</div>
                                    <div class="profile-info-value">
									<textarea class="col-sm-12 col-xs-12 "
                                              style="resize:none;padding-left:3px !important;"
                                              maxlength="200" rows="3" id="description_add"
                                              name="description"></textarea>
                                    </div>
                                </div>
                            </div>

                            <div class="space-4"></div>
                            <button class="btn btn-sm btn-success" type="button" onclick="doAdd()">
                                <i class="ace-icon fa fa-check"></i> 保存
                            </button>
                            &nbsp; &nbsp; &nbsp;
                            <button class="btn btn-sm btn-purple" type="button" onclick="onReset()">
                                <i class="ace-icon fa fa-undo"></i> 重置
                            </button>
                            <%--<div class="clearfix form-actions col-sm-12 col-xs-12" style="display:none;">

                            </div>--%>
                        </form>
                    </div>
                    <div class="space-24"></div>
                </div>

                <div style="display:none;" id="edit">
                    <div align="center">
                        <form class="form-horizontal" method="post" action="#" id="form_dep" target="frmright"
                              role="form">
                            <div class="profile-user-info profile-user-info-striped">
                                <div class="profile-info-row">
                                    <div class="profile-info-name">组织名称：</div>
                                    <div class="profile-info-value">
                                        <input type="hidden" id="id_edit" name="id"/>
                                        <input type="text" id="name_edit" name="name" placeholder="必填项，长度不能超过12位"
                                               class="col-xs-12 col-sm-12"/>
                                    </div>
                                </div>
                                <div class="profile-info-row">
                                    <div class="profile-info-name"> 上级目录：</div>
                                    <div class="profile-info-value">
                                        <input type="text" id="pId_edit" name="parent" style="display:none"/>
                                        <input type="text" id="pName_edit" disabled class="col-xs-12 col-sm-12"/>
                                    </div>
                                </div>
                                <div class="profile-info-row">
                                    <div class="profile-info-name">联系人：</div>
                                    <div class="profile-info-value">
                                        <input type="text" id="contact_edit" name="contact"
                                               class="col-xs-12 col-sm-12"/>
                                    </div>
                                </div>
                                <div class="profile-info-row">
                                    <div class="profile-info-name">联系电话：</div>
                                    <div class="profile-info-value">
                                        <input type="text" id="tel_edit" name="tel" class="col-xs-12 col-sm-12"/>
                                    </div>
                                </div>
                                <div class="profile-info-row">
                                    <div class="profile-info-name">联系地址：</div>
                                    <div class="profile-info-value">
                                        <input type="text" id="address_edit" name="address"
                                               class="col-xs-12 col-sm-12"/>
                                    </div>
                                </div>
                                <div class="profile-info-row">
                                    <div class="profile-info-name"> 描述：</div>
                                    <div class="profile-info-value">
									<textarea class="col-sm-12 col-xs-12 "
                                              style="resize:none;padding-left:3px !important;"
                                              maxlength="200" rows="3" id="description_edit"
                                              name="description"></textarea>
                                    </div>
                                </div>
                            </div>

                            <div class="space-4"></div>
                            <button class="btn btn-sm btn-success" type="button" onclick="doEdit()">
                                <i class="ace-icon fa fa-check"></i> 保存
                            </button>
                            &nbsp; &nbsp; &nbsp;
                            <button class="btn btn-sm btn-purple" type="button" onclick="onReset()">
                                <i class="ace-icon fa fa-undo"></i> 重置
                            </button>
                            <%--<div class="clearfix form-actions col-sm-12 col-xs-12" style="display:none;">

                            </div>--%>
                        </form>
                    </div>
                    <div class="space-24"></div>
                </div>
            </div>
        </div>
    </div>
</div>
</div>

<script type="text/javascript">
    //导入脚本
    var scripts = [null,
        "${ctx}/assets/admin/LingUI/js/jqGrid/jquery.jqGrid.js",
        "${ctx}/assets/admin/LingUI/viljs/list.js",
        "${ctx}/assets/admin/LingUI/js/control.js",
        "${ctx}/assets/admin/LingUI/js/lui.jiantingdiv.js",
        "${ctx}/assets/admin/LingUI/js/jquery/jquery-form.js",
        "${ctx}/assets/admin/LingUI/datetimepicker/jquery.datetimepicker.js",//下拉框控件
        null];

    /**
     * 设置全局变量
     */
    var tree = "treeDemo";//树id
    var $tree = $("#treeDemo");
    var zTree; //树对象
    ace.load_ajax_scripts(scripts, function () {

        jQuery(function ($) {
            $('input, textarea').placeholder(); //空输入框中占位符
            $(".form-actions").width($(".widget-container-col").width() - 40);
            //日期下拉框
            $(".datepicker").datetimepicker({
                value: $(this).attr("value"),
                format: 'Y-m-d',		//格式化
                timepicker: false	//不允许显示时间
            }).next().on(ace.click_event, function () {
                $(this).prev().focus();
            });
            var setting = {
                async: {
                    autoParam: ["id=id"],
                    enable: true,
                    type: "GET",
                    dataType: 'json',
                    url: "${ctx}/${frameworkPath}/org/children"
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                view: {
                    addHoverDom: addHoverDom,		//用于当鼠标移动到节点上时，显示用户自定义控件
                    removeHoverDom: removeHoverDom,	//用于当鼠标移出节点时，隐藏用户自定义控件
                    selectedMulti: false			//设置是否允许同时选中多个节点。默认值: true
                },
                edit: {
                    enable: false,
                    editNameSelectAll: false,
                    showRemoveBtn: true,			//显示修改按钮
                    showRenameBtn: true			//显示删除按钮
                },
                data: {								//确定 zTree 初始化时的节点数据、异步加载时的节点数据、或 addNodes 方法中输入的 newNodes
                    simpleData: {					//数据是否采用简单数据模式 (Array)
                        enable: true  				//不需要用户再把数据库中取出的 List 强行转换为复杂的 JSON 嵌套格式
                    }
                },
                callback: {
                    onClick: onClick,				//树节点点击事件
                    //beforeEditName: beforeEditName, //编辑事件
                    //beforeRemove: beforeRemove,		//删除事件
                    onAsyncSuccess: onAsyncSuccess	//加载完成后回调
                }
            };
            zTree = $.fn.zTree.init($tree, setting); //树初始化

            /**
             *    树节点点击事件
             */
            function onClick(event, treeId, treeNode, clickFlag) {
                debugger;
                console.log(treeNode);
                formView();						//表单视图显示
                setFromValue_view(treeNode);			//设置表单数据
            }

            /**
             * 编辑事件
             */
            function beforeEditName(treeId, treeNode) {
                formEdit();							//表单编辑页面显示
                setFromValue_edit(treeNode);				//设置表单数据
                return false;
            }

            /**
             * 删除事件
             */
            function beforeRemove(treeId, treeNode) {
                if (!treeNode.pId) {
                    lui.info("根节点不能删除！");
                    return false;
                }
                if (treeNode.children.length > 0) {
                    lui.info("存在子节点不能删除！");
                    return false;
                }
                lui.confirm("确认删除 节点 -- " + treeNode.name + " 吗？"
                        , function () {
                            confirmDelete(treeNode);
                        }, function () {
                        });
                return false;
            }

            /**
             *    显示节点的自定义控件
             */
            function addHoverDom(treeId, treeNode) {
                var sObj = $("#" + treeNode.tId + "_span");
                var addStr = null;
                var editStr = null;
                var removeStr = null;
                if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
                if (treeNode.editNameFlag || $("#editBtn_" + treeNode.tId).length > 0) return;
                if (treeNode.editNameFlag || $("#removeBtn_" + treeNode.tId).length > 0) return;
                <shiro:hasPermission name="ORG_CREATE">
                addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='新增' onfocus='this.blur();'></span>";
                </shiro:hasPermission>
                <shiro:hasPermission name="ORG_EDIT">
                editStr = "<span class='button edit' id='editBtn_" + treeNode.tId + "' title='编辑' onfocus='this.blur();'></span>";
                </shiro:hasPermission>
                <shiro:hasPermission name="ORG_DELETE">
                removeStr = "<span class='button remove' id='removeBtn_" + treeNode.tId + "' title='删除' onfocus='this.blur();'></span>";
                </shiro:hasPermission>

                if (treeNode.pId == null) {
                    sObj.append(addStr);
                }
                else {
                    sObj.append(addStr);
                    sObj.append(editStr);
                    sObj.append(removeStr);
                }
                $(document).on("click", "#addBtn_" + treeNode.tId, function (e) {
                    formAdd(treeId, treeNode); //表单新增页面
                    return false;
                }).on("click", "#editBtn_" + treeNode.tId, function (e) {
                    beforeEditName(treeId, treeNode); //表单编辑页面
                    return false;
                }).on("click", "#removeBtn_" + treeNode.tId, function (e) {
                    beforeRemove(treeId, treeNode); //表单删除页面
                    return false;
                });
            };

            /**
             * 隐藏节点的自定义控件
             */
            function removeHoverDom(treeId, treeNode) {
                if ($("#addBtn_" + treeNode.tId).size() > 0)
                    $("#addBtn_" + treeNode.tId).off().remove();
                if ($("#editBtn_" + treeNode.tId).size() > 0)
                    $("#editBtn_" + treeNode.tId).off().remove();
                if ($("#removeBtn_" + treeNode.tId).size() > 0)
                    $("#removeBtn_" + treeNode.tId).off().remove();
            };

            /**
             * 数据加载完成后触发事件
             */
            function onAsyncSuccess() {
                treeOnAsyncSuccess();//数据加载完成后触发事件
            }

        });
        //验证
        $("#form_dep").validate({
            rules: {
                errorElement: 'div',
                errorClass: 'help-block',
                focusInvalid: false,
                'name': {required: true, maxlength: 12},
                'parent': {required: true},
                'description': {required: false, maxlength: 150}
            },
            messages: {
                "name": {
                    required: "<font color='#d16e6c'>部门名称不能为空！</font>",
                    maxlength: "<font color='#d16e6c'>部门名称不能超过12位！</font>"
                },
                "description": {
                    required: "<font color='#d16e6c'>描述不能为空！</font>",
                    maxlength: "<font color='#d16e6c'>描述不能超过150位！</font>"
                }
            }
        });

        //验证
        $("#form_dep_add").validate({
            rules: {
                errorElement: 'div',
                errorClass: 'help-block',
                focusInvalid: false,
                'name': {required: true, maxlength: 12},
                'parent': {required: true},
                'order':{required: true,digits:true},
                'description': {required: false, maxlength: 150}
            },
            messages: {
                "name": {
                    required: "<font color='#d16e6c'>部门名称不能为空！</font>",
                    maxlength: "<font color='#d16e6c'>部门名称不能超过12位！</font>"
                },
                "order": {
                    required: "<font color='#d16e6c'>排序字段不能为空！</font>"
                },
                "description": {
                    required: "<font color='#d16e6c'>描述不能为空！</font>",
                    maxlength: "<font color='#d16e6c'>描述不能超过150位！</font>"
                }
            }
        });

    });

    /**
     * 数据加载完成后触发事件
     */
    var treeOnAsyncSuccess = function () {
        /*var node = zTree.getNodes()[0];
         zTree.selectNode(node);
         zTree.expandNode(node,true,true,true);
         //触发跟节点的点击事件
         zTree.setting.callback.onClick(null, zTree.setting.treeId, node);*/

        asyncNodes(zTree.getNodes());
        zTree.expandAll(true);

        //select root node
        var node = zTree.getNodes()[0];
        zTree.selectNode(node);
        zTree.setting.callback.onClick(null, zTree.setting.treeId, node);
    };

    function asyncNodes(nodes) {
        if (!nodes) return;
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        for (var i = 0, l = nodes.length; i < l; i++) {
            if (nodes[i].isParent && nodes[i].zAsync) {
                asyncNodes(nodes[i].children);
            }
            else {
                zTree.reAsyncChildNodes(nodes[i], "refresh", true);
            }
        }
    }

    /**
     * 表单修改
     */
    function formEdit() {
        $("#view").hide();
        $("#add").hide();
        $("#edit").show();
        setTimeout(function () {
            $(".form-actions").show();
        }, 250);
    }
    /**
     * 表单视图
     */
    function formView() {
        $("#view").show();
        $("#edit").hide();
        $("#add").hide();
    }

    function formAddShow() {
        $("#add").show();
        $("#edit").hide();
        $("#view").hide();
    }
    /**
     * 表单新增
     */
    function formAdd(treeId, treeNode) {
        removeFromValue(); 						//置空表单值
        $("#pId_add").val(treeNode.id);		//设置父节点id
        $("#pName_add").val(treeNode.name);	//设置父节点名称
        formAddShow();								//显示表单编辑
    }

    /**
     * 设置表单中的值
     */
    function setFromValue(treeNode) {
        $("#id_edit").val(treeNode.id);
        $("#name_edit").val(treeNode.name);
        $("#description_edit").val(treeNode.description);
        $("#pId_edit").val(treeNode.pId);
        $("#pName_edit").val(treeNode.pName);

        $("#id_view").text(treeNode.id);
        $("#name_view").text(treeNode.name);
        $("#parent_view").text(treeNode.pName);
        $("#description_view").text(treeNode.description);
    }

    //加载编辑数据
    function setFromValue_edit(treeNode) {
        $.ajax({
            type: 'GET',
            cache: false,
            dataType: 'json',
            url: '${ctx}/${frameworkPath}/org/view/' + treeNode.id,
            success: function (data) {
                var org = data.rows;
                $("#id_edit").val(treeNode.id);
                $("#name_edit").val(treeNode.name);
                $("#description_edit").val(org.description);
                $("#pId_edit").val(treeNode.pId);
                $("#pName_edit").val(treeNode.pName);
                $("#contact_edit").val(org.contact);
                $("#tel_edit").val(org.tel);
                $("#address_edit").val(org.address);
            },
            error: function (XmlHttpRequest, textStatus, errorThrown) {
                alert('error');
            }
        });
    }

    //加载view数据
    function setFromValue_view(treeNode) {
        $.ajax({
            type: 'GET',
            cache: false,
            dataType: 'json',
            url: '${ctx}/${frameworkPath}/org/view/' + treeNode.id,
            success: function (data) {
                debugger;
                var org = data.rows;
                $("#id_view").text(org.id);
                $("#name_view").text(org.name);
                $("#parent_view").text(treeNode.pName);
                $("#contact_view").text(org.contact);
                $("#tel_view").text(org.tel);
                $("#address_view").text(org.address);
                $("#description_view").text(org.description);
            },
            error: function (XmlHttpRequest, textStatus, errorThrown) {
                alert('error');
            }
        });
    }

    /**
     * 清空表单中的值
     */
    function removeFromValue() {
        $("#id_edit").val("");
        $("#name_edit").val("");
        $("#description_edit").val("");
        $("#pId_edit").val("");
        $("#contact_edit").val("");
        $("#tel_edit").val("");
        $("#address_edit").val("");

        $("#id_add").val("");
        $("#name_add").val("");
        $("#description_add").val("");
        $("#pId_add").val("");
        $("#contact_add").val("");
        $("#tel_add").val("");
        $("#address_add").val("");

        $("#name_view").text("");
        $("#parent_view").text("");
        $("#description_view").text("");
        $("#contact_view").val("");
        $("#tel_view").val("");
        $("#address_view").val("");
    }

    function doAdd() {
        var valid = $('#form_dep_add').valid();
        if (valid) {
            $("#form_dep_add").ajaxSubmit({
                type: 'post',
                url: '${ctx}/${frameworkPath}/org/create',
                dataType: 'json',
                //beforeSubmit :function(formData, jqForm, options){},
                success: function (message) {
                    if (message.success) {
                        lui.info('保存成功');
                        var selectNode = zTree.getNodesByParam("id", $("#pId_add").val(), null)[0];
                        zTree.reAsyncChildNodes(selectNode, "refresh");	//刷新树

                        treeOnAsyncSuccess = function () {
                            asyncNodes(zTree.getNodes());
                            zTree.expandAll(true);
                            var newNode = zTree.getNodesByParam("id", message.id, null)[0];//当前选中的节点
                            zTree.selectNode(newNode);
                            zTree.setting.callback.onClick(null, zTree.setting.treeId, newNode);//选中节点
                        }
                    }
                    else {
                        lui.info(message.error);
                    }
                }
            });
        }
    }

    /**
     * save
     */
    function doEdit() {
        var valid = $('#form_dep').valid();
        if (valid) {
            $("#form_dep").ajaxSubmit({
                type: 'post',
                url: '${ctx}/${frameworkPath}/org/edit/' + $('#id_edit').val(),
                dataType: 'json',
                //beforeSubmit :function(formData, jqForm, options){},
                success: function (message) {
                    if (message.success) {
                        lui.info('保存成功');
                        //刷新树节点的名称
                        var newNode = zTree.getNodesByParam("id", $("#id_edit").val(), null)[0];//当前选中的节点
                        newNode.name = $("#name_edit").val();
                        zTree.updateNode(newNode);
                        zTree.selectNode(newNode);
                        zTree.setting.callback.onClick(null, zTree.setting.treeId, newNode);
                    }
                    else if (message.success == false) {
                        lui.info(message.error);
                    }
                }
            });
        }
    }

    /**
     * 重置
     */
    function onReset() {
        var id = $("#id_edit").val();
        var treeNodes = zTree.getNodesByParam("id", id, null);
        if (treeNodes.length > 0) {
            setFromValue(treeNodes[0]);				//设置表单中的数据
        } else {
            var pId = $("#pId_edit").val();
            var pName = $("#pName_edit").val();
            removeFromValue();						//清除表单中的数据
            $("#pId_edit").val(pId);		//设置父节点id
            $("#pName_edit").val(pName);	//设置父节点名称
        }
    }


    /**
     *    删除确认
     */
    function confirmDelete(treeNode) {
        var idArray = new Array();
        idArray.push(treeNode.id);
        $.ajax({
            type: "post",
            url: "${ctx}/${frameworkPath}/org/delete",
            data: {'ids': idArray},
            dataType: 'json',
            traditional: true,
            success: function (message) {
                if (message.success) {
                    lui.info("删除成功！");
                    zTree.removeNode(zTree.getNodesByParam("id", treeNode.id, null)[0]);//移除节点
                    var pNode = zTree.getNodesByParam("id", treeNode.pId, null)[0];//获取父节点
                    zTree.setting.callback.onClick(null, zTree.setting.treeId, pNode);
                }
                else {
                    lui.info(message.content);
                }
            }
        });
    }

</script>